/*
 * @Author: xiaosihan 
 * @Date: 2022-11-20 09:55:59 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2022-11-20 10:03:13
 */


//mesh
import { BufferGeometry, Camera, Clock, CylinderGeometry, DoubleSide, Group, Material, Mesh, Scene, ShaderChunk, ShaderMaterial, WebGLRenderer } from "three";
import threeLoader from "three-base/threeLoader";
import { degToRad } from "three/src/math/MathUtils";
import offsetMap from "./Water_1_M_Normal.jpg";
import waterMapPNG from "./waterMap.png";
import penquanGLB from "./penquan.glb?url";


// 喷泉
export default class Fountain extends Mesh {
    constructor() {
        super();
    }

    castShadow = false;

    geometry = (() => {
        const geometry = new CylinderGeometry(0, 0.1, 2, 50, 50, true);
        geometry.translate(0, 1, 0);
        return geometry;
    })();

    renderOrder = 9;

    material = new ShaderMaterial({
        uniforms: {
            offsetY: { value: 0 }, // uvy 的偏移
            map: { value: threeLoader.getTexture(waterMapPNG) }, // 贴图纹理
            offsetMap: { value: threeLoader.getTexture(offsetMap) } //偏移纹理
        },
        vertexShader: `
            ${ShaderChunk.common}
            ${ShaderChunk.logdepthbuf_pars_vertex}
            uniform sampler2D map;
            varying vec2 vUv;
            varying vec3 vPosition;
            uniform sampler2D offsetMap;
            uniform float offsetY;
            void main() {
                vUv = uv;
                vPosition = position;
                vPosition.y = min(vPosition.y, 1.6);

                vec4 color = texture2D(map, vUv + vec2(0.0, offsetY) + (texture2D(offsetMap, vUv).xy/10.0) );
                float offset = max(max(color.x, color.y), color.z);

                gl_Position = projectionMatrix * modelViewMatrix * vec4( vPosition + (normal * offset * ((1.0 - vUv.y)/5.0) ), 1.0 );

                ${ShaderChunk.logdepthbuf_vertex}
            }
        `,
        fragmentShader: `
            ${ShaderChunk.logdepthbuf_pars_fragment}
            uniform sampler2D map;
            uniform sampler2D offsetMap;
            uniform float offsetY;
            varying vec2 vUv;
            void main() {
                gl_FragColor = texture2D(map, vUv + vec2(0.0, offsetY) + (texture2D(offsetMap, vUv).xy/10.0) );
                float opacity = max(max(gl_FragColor.x, gl_FragColor.y), gl_FragColor.z);
                gl_FragColor = vec4(1.0, 1.0, 1.0, opacity * opacity);
                ${ShaderChunk.logdepthbuf_fragment}
            }
        `,
        // blending: NoBlending, // 渲染时不与背景融合计算 直接替换
        depthTest: true,
        depthWrite: true,
        transparent: true,
        side: DoubleSide
    });

    clock = new Clock();

    onBeforeRender = (renderer: WebGLRenderer, scene: Scene, camera: Camera, geometry: BufferGeometry, material: Material, group: Group) => {
        const delta = this.clock.getDelta() / 2;
        this.material.uniforms.offsetY.value += delta;
    };

}

